package cn.edu.lingnan.lsqn.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import cn.edu.lingnan.lsqn.dao.IColumnDao;
import cn.edu.lingnan.lsqn.dao.IGroupDao;
import cn.edu.lingnan.lsqn.model.Column;
import cn.edu.lingnan.lsqn.model.Group;
import cn.edu.lingnan.lsqn.model.LsqnException;

@Service("columnService")
public class ColumnService implements IColumnService {
	private IGroupDao groupDao;
	private IColumnDao columnDao;

	public IGroupDao getGroupDao() {
		return groupDao;
	}

	@Inject
	public void setGroupDao(IGroupDao groupDao) {
		this.groupDao = groupDao;
	}

	public IColumnDao getColumnDao() {
		return columnDao;
	}

	@Inject
	public void setColumnDao(IColumnDao cloumnDao) {
		this.columnDao = cloumnDao;
	}

	private void addGroupColumn(Column column, int[] g_id) {
		List<Group> groups = groupDao.list();
		Map<Integer, Group> cids = new HashMap<Integer, Group>();
		for (Group g : groups) {
			cids.put(g.getId(), g);
		}
		for (int id : g_id) {
			if (cids.containsKey(id))
				columnDao.addGroupColumn(cids.get(id), column);
		}
	}

	@Override
	public void add(Column column, int[] g_id) {
		if (g_id == null || g_id.length <= 0)
			throw new LsqnException("请设置可访问该栏目的组");
		try{
			
			columnDao.add(column);
		}catch (Exception e) {
			System.out.println("columndao:"+e.getMessage());
		}
		try{
			
			addGroupColumn(column, g_id);
		}catch (Exception e) {
			System.out.println("GroupColumn"+e.getMessage());
		}
	}

	@Override
	public void delete(int id) {
		columnDao.deleteGroupColumn(id);
		columnDao.delete(id);
	}

	@Override
	public Column load(int id) {
		return columnDao.load(id);
	}

	@Override
	public void update(Column column) {
		columnDao.update(column);
	}

	@Override
	public List<Column> listColumn() {
		return columnDao.list();
	}

	@Override
	public List<Column> listByParent(Integer pid) {
		if(pid==null)
			return columnDao.listColumnParent();
		else
			return columnDao.listByParent(pid);
	}

	@Override
	public int getMaxOrder(Integer pid) {
		return columnDao.getMaxOrder(pid);
	}

	@Override
	public List<Column> listByGroup(Integer gid) {
		return columnDao.listByGroup(gid);
	}

}
